package net.maku.security.service;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.maku.framework.security.mobile.MemberAuthDetailsService;
import net.maku.framework.security.user.UserDetail;
import net.maku.member.dao.MemberUserDao;
import net.maku.member.entity.MemberUserEntity;
import net.maku.system.dao.SysOrgDao;
import net.maku.system.entity.SysOrgEntity;
import net.maku.system.service.SysUserDetailsService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * @author Administrator
 */
@Service
@AllArgsConstructor
@Slf4j
public class MemberAuthDetailsServiceImpl implements MemberAuthDetailsService {

    private final SysUserDetailsService sysUserDetailsService;
    private final MemberUserDao memberUserDao;
    private final SysOrgDao sysOrgDao;

    @Override
    public UserDetails loadUserByMobile(String mobile) throws UsernameNotFoundException {
        MemberUserEntity memberUserEntity = memberUserDao.selectOne(new LambdaQueryWrapper<MemberUserEntity>().eq(MemberUserEntity::getMobile, mobile));
        if (memberUserEntity == null) {
            log.error("用户名不存在：mobile={}",mobile);
            throw new UsernameNotFoundException("用户不存在");
        }
        UserDetail userDetail = BeanUtil.copyProperties(memberUserEntity, UserDetail.class);
        SysOrgEntity sysOrgEntity = sysOrgDao.selectById(memberUserEntity.getOrgId());
        if(sysOrgEntity != null){
            userDetail.setOrgName(sysOrgEntity.getUnionAbbreviation());
        }
        return sysUserDetailsService.getUserDetails(userDetail);
    }
}
